package top.huxy.boot.controller.admin;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.huxy.boot.util.StringUtils;
import top.huxy.boot.util.obj.Result;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

@RestController
@Slf4j
public class AdminImageController {

    @Value("${huxy.app.static}")
    private String imgDir;

    @PostMapping("/admin/img/upload")
    public Result uploadImage(MultipartFile file) throws IOException {
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return Result.clientError("只能上传图片");
        }
        long size = file.getSize();
        if (file.isEmpty() || size < 1) {
            return Result.clientError("图片为空");
        }
        if (size > 1024 * 1024 * 30) {
            return Result.clientError("图片大小限制30MB");
        }

        File dest = new File(imgDir);
        if(dest.isDirectory()&&dest.exists()){
            byte[] targetFileBytes = file.getBytes();
            if(targetFileBytes.length >0){
                //从目录中读取大小相同的文件
                File[] files = dest.listFiles(f -> f.length() == size);
                if(files!=null&&files.length!=0){
                    for (File f : files) {
                        try(FileInputStream fileInputStream = new FileInputStream(f)){
                            byte[] b1 = new byte[(int) f.length()];
                            fileInputStream.read(b1);
                            if(Arrays.equals(targetFileBytes, b1)){
                                //图片一致，就不重新保存，返回旧图片就行了
                                return Result.success(f.getName(),"旧图片");
                            }
                        }catch (Exception e){
                            log.error("未捕获的异常",e);
                        }
                    }
                }
            }
        }else{
            if(dest.isFile()){
                return Result.serverError("dest path is file");
            }
            if(!dest.mkdirs()){
                return Result.serverError("mkdirs fail");
            }
        }

        dest = null;

        String originalFilename = file.getOriginalFilename();
        int i = originalFilename.lastIndexOf('.');
        String hzm = i == -1 ? "" : originalFilename.substring(i);
        String destFilename = StringUtils.unique()+hzm;

        File destFile = new File(imgDir + destFilename);
        file.transferTo(destFile);
        return Result.success(destFilename);
    }
}
